package com.study.bigevent.service.impl;

import com.study.bigevent.mapper.UserMapper;
import com.study.bigevent.pojo.User;
import com.study.bigevent.service.UserService;
import com.study.bigevent.utils.Md5Util;
import com.study.bigevent.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper; // 自动注入UserMapper，用于操作数据库中的用户表

    @Override
    public User findByUserName(String username) {
        // 根据用户名查询用户信息
        User u = userMapper.findByUserName(username);
        return u;
    }

    @Override
    public void register(String username, String password) {
        // 注册新用户，将密码进行MD5加密后存入数据库
        String md5Pwd = Md5Util.getMD5String(password);
        userMapper.add(username, md5Pwd);
    }

    @Override
    public void update(User user) {
        // 更新用户信息，设置更新时间并保存到数据库
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
    }

    @Override
    public void updateAvatar(String avatarUrl) {
        // 更新用户头像，从线程上下文中获取用户ID并更新头像URL
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        userMapper.updateAvatar(avatarUrl, id);
    }

    @Override
    public void updatePwd(String newPwd) {
        // 更新用户密码，从线程上下文中获取用户ID并将新密码进行MD5加密后更新
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        userMapper.updatePwd(Md5Util.getMD5String(newPwd), id);
    }
}